package com.lzj.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzj.admin.model.CountResultModel;
import com.lzj.admin.pojo.Goods;
import com.lzj.admin.pojo.PurchaseList;
import com.lzj.admin.mapper.PurchaseListMapper;
import com.lzj.admin.pojo.PurchaseListGoods;
import com.lzj.admin.query.PurchaseListQuery;
import com.lzj.admin.service.IGoodsService;
import com.lzj.admin.service.IGoodsTypeService;
import com.lzj.admin.service.IPurchaseListGoodsService;
import com.lzj.admin.service.IPurchaseListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.admin.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 进货单 服务实现类
 * </p>
 *
 * @author luoyoumou
 * @date 2022-12-14
 */
@Service
public class PurchaseListServiceImpl extends ServiceImpl<PurchaseListMapper, PurchaseList> implements IPurchaseListService {

    @Resource
    private IPurchaseListGoodsService purchaseListGoodsService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IGoodsTypeService goodsTypeService;


    /**
     * --进货单号格式--
     * JH--固定
     * 20220101--时间工具类
     * 0001--数量递增
     * @return
     */
    @Override
    public String getNextPurchaseNumber() {
        // JH20210101XXXX
        try {
            StringBuffer stringBuffer =new StringBuffer();
            stringBuffer.append("JH");
            stringBuffer.append(DateUtil.getCurrentDateStr());
            String purchaseNumber = this.baseMapper.getNextPurchaseNumber();
            if(null !=purchaseNumber){
                stringBuffer.append(StringUtil.formatCode(purchaseNumber));
            }else{
                stringBuffer.append("0001");
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 商品入库
     * @param purchaseList
     * @param plgList
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void savePurchaseList(PurchaseList purchaseList, List<PurchaseListGoods> plgList) {
        AssertUtil.isTrue(null == purchaseList.getSupplierId()|| 0 == purchaseList.getSupplierId() ,"请选择供应商！");
        AssertUtil.isTrue(CollectionUtils.isEmpty(plgList),"请添加商品！");
        // AssertUtil.isTrue(null == purchaseList.getAmountPaid()|| 0 >= purchaseList.getAmountPaid() ,"实付金额 必须 >0 ！");
        AssertUtil.isTrue(null == purchaseList.getAmountPaid()|| BigDecimal.ZERO.compareTo(purchaseList.getAmountPaid()) > -1 ,"实付金额 必须 >0 ！");
        purchaseList.setCreateDate(new Date());
        AssertUtil.isTrue(!(this.save(purchaseList)),"记录添加失败!");
        PurchaseList temp = this.getOne(new QueryWrapper<PurchaseList>().eq("purchase_number",purchaseList.getPurchaseNumber()));
        plgList.forEach(plg->{
            AssertUtil.isTrue(null == plg.getNum()|| 1 > plg.getNum(),"请检查：每件商品的 数量 必须 >=1 ！");
            plg.setPurchaseListId(temp.getId());
            plg.setFpyName(PinYinUtil.getFirstSpell(plg.getName()));
            Goods goods = goodsService.getById(plg.getGoodsId());
            goods.setInventoryQuantity(goods.getInventoryQuantity()+plg.getNum());
            goods.setLastPurchasingPrice(plg.getPrice());
            goods.setState(2);
            goodsService.updateById(goods);
        });
        AssertUtil.isTrue(!(purchaseListGoodsService.saveBatch(plgList)),"记录添加失败!");


    }

    /**
     * 记录查询
     * @param purchaseListQuery
     * @return
     */
    @Override
    public Map<String, Object> purchaseList(PurchaseListQuery purchaseListQuery) {
        //准备分页参数
        IPage<PurchaseList> page = new Page<PurchaseList>(purchaseListQuery.getPage(),purchaseListQuery.getLimit());
        page =  this.baseMapper.purchaseList(page,purchaseListQuery);
        return PageResultUtil.getResult(page.getTotal(),page.getRecords());
    }

    /**
     * 删除进货单
     * 1.进货单商品记录删除
     * 2.进货单记录删除
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deletePurchaseList(Integer id) {
        AssertUtil.isTrue(!(purchaseListGoodsService.remove(new QueryWrapper<PurchaseListGoods>().eq("purchase_list_id",id))),
                "记录删除失败!");
        AssertUtil.isTrue(!(this.removeById(id)),"记录删除失败!");
    }

    /**
     * 进货单 - 结算功能实现 (修改支付付状态为1)
     * @param id
     */
    @Override
    //事务控制
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updatePurchaseListState(Integer id) {
        //根据pid查询待结算记录，返回集合
        PurchaseList purchaseList =this.getById(id);
        //判断集合是否为空，为空提示信息
        AssertUtil.isTrue(null == purchaseList,"待结算的进货单记录不存在!");
        //判断交易状态，getState()==1提示已经支付
        AssertUtil.isTrue(purchaseList.getState()==1,"进货单记录已支付!");
        //更新交易状态
        purchaseList.setState(1);
        //判断交易状态，取反,结算失败
        AssertUtil.isTrue(!(this.updateById(purchaseList)),"进货单记录结算失败!");
    }

    /**
     * 分页查询
     *   查总数
     *   查当前页列表
     * 采购统计，查总数，查当前页列表
     * 数据库主表和从表都查询了，是一比多的查询
     * mybatisplus只统计主表的记录
     * 主表和从表数据都查了，会导致单号重复，前后端数据对不上
     * @param purchaseListQuery
     * @return
     */
    @Override
    public Map<String, Object> countPurchase(PurchaseListQuery purchaseListQuery) {
        if(null != purchaseListQuery.getTypeId()){
            List<Integer> typeIds= goodsTypeService.queryAllSubTypeIdsByTypeId(purchaseListQuery.getTypeId());
            purchaseListQuery.setTypeIds(typeIds);
        }
        if( null != purchaseListQuery.getTypeName()){
            purchaseListQuery.setTypeIds(goodsTypeService.queryAllSubTypeIdsByTypeId(purchaseListQuery.getTypeName()));
        }
        purchaseListQuery.setIndex((purchaseListQuery.getPage()-1)*purchaseListQuery.getLimit());
        Long count  = this.baseMapper.countPurchaseTotal(purchaseListQuery);
        List<CountResultModel> list =this.baseMapper.countPurchaseList(purchaseListQuery);
        return PageResultUtil.getResult(count,list);
    }

}
